﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace evolution
{
    class Program
    {
        const int N = 30;
        static int[,] matrix = new int[N,N];

        static void ShowMatrix()
        {
            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < N; j++)
                    if (matrix[i, j] == 1)
                        Console.Write('*');
                    else
                        Console.Write(' ');
                Console.WriteLine();
            }
            Console.Write("\nPress space to transform or press 'q' to exit\n\n");
        }
        
        static void Main(string[] args)
        {
            Random bin = new Random();
            for (int i = 0; i < N; i++)
                for (int j = 0; j < N; j++)
                    matrix[i, j] = bin.Next(2);

            ShowMatrix();

            ConsoleKeyInfo key = new ConsoleKeyInfo();
            do
            {
                key = Console.ReadKey();

                if (key.KeyChar == ' ')
                { 
                    int[,] temp = new int [N,N];
                    for (int i = 0; i < N; i++)
                        for (int j = 0; j < N; j++)
                            temp[i, j] = matrix[i, j];
                    
                    for (int i = 0; i < N; i++)
                        for (int j = 0; j < N; j++)
                        {
                            int count = 0, n = 0;
                            for (int k = i - 1; k <= i + 1; k++)
                                for (int l = j - 1; l <= j + 1; l++)
                                    if (k >= 0 && k < N && l >= 0 && l < N)
                                    {
                                        n++;
                                        if (temp[k, l] == 1)
                                            count++;
                                    }

                            if (temp[i, j] == 0 && count >= 2)
                                matrix[i, j] = 1;
                            if (temp[i, j] == 1 && count == n)
                                matrix[i, j] = 0;
                        }

                    ShowMatrix();
                }
            }
            while (key.KeyChar != 'q');
        }
    }
}
